from django import http
from django.contrib.auth import login
from django.http import JsonResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection

from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import encrypt_openid, decode_openid
from apps.users.models import User
from utils.response_code import RETCODE


from QQLoginTool.QQtool import OAuthQQ
from meiduo_mall.settings import QQ_CLIENT_ID, QQ_CLIENT_SECRET, QQ_REDIRECT_URI

# 跳转到qq的接口., 点击qq登陆后
class QQaothView(View):
    def get(self,request):
        state = 'abcdef'
        qq = OAuthQQ(client_id=QQ_CLIENT_ID,
                     client_secret=QQ_CLIENT_SECRET,
                     redirect_uri=QQ_REDIRECT_URI,
                     state=state)
        # 使用这个方法得到url
        login_url = qq.get_qq_url()
        return JsonResponse({'code':RETCODE.OK,'errmsg':'ok','login_url':login_url})

# 跳转到绑定界面
class Auth_callback(View):
    # 跳转到绑定界面后取到这俩值
    def get(self,request):
        code = request.GET.get('code')
        state = request.GET.get('state')

        # 如果没有code参数
        if code is None:
            return http.HttpResponseBadRequest('code参数缺失')
        qq = OAuthQQ(client_id=QQ_CLIENT_ID,
                     client_secret=QQ_CLIENT_SECRET,
                     redirect_uri=QQ_REDIRECT_URI,
                     state=state)
        taken = qq.get_access_token(code)

        openid = qq.get_open_id(taken)

        try:
            # 查询有没有openid
            qquser = OAuthQQUser.objects.get(openid = openid)
        except OAuthQQUser.DoesNotExist:

            # 加密openid
            access_token=encrypt_openid(openid)

            # 说明没查询到open,说明没有绑定过,去绑定界面
            return render(request,'oauth_callback.html',context={'openid':access_token})
        else:
            # 查询到了记录,说明绑定过,登陆
           # 保持会话状态
            login(request,qquser.user)
            response =  redirect(reverse('contents:index'))
            # 设置cookie,让首页显示用户名
            response.set_cookie('username',qquser.user.username,max_age=3600)
            return response

    def post(self,request):
        # 1.接收数据
        mobile = request.POST.get('mobile')
        password = request.POST.get('pwd')
        sms_code = request.POST.get('sms_code')
        access_token = request.POST.get('openid')
        openid = decode_openid(access_token)
        # 2.校验数据
        if not all([mobile,password,sms_code,openid]):
            return http.HttpResponseBadRequest("缺少参数")
        import re
        # 验证手机是否符合规则
        if not re.match(r'1[3-9]\d{9}', mobile):
            return http.HttpResponseBadRequest('手机号不符合规则')
        # 验证密码是否符合规则
        if not re.match(r'[0-9A-Za-z]{8,20}', password):
            return http.HttpResponseBadRequest('密码不符合规则')
        # 验证短信验证码是否和输入的一致.
        redis_conn = get_redis_connection('code')
        redis_sms_code = redis_conn.get('sms_%s'%mobile)

        # 首先判断短信验证码过期没
        if redis_sms_code is None:
            return http.HttpResponseBadRequest("短信验证码 过期了")
        if redis_sms_code.decode() != sms_code:
            return http.HttpResponseBadRequest("短信验证码不一致")

        # 3.根据手机号进行用户信息的判断
        try:
            user = User.objects.get(mobile=mobile)
        # 如果手机号没有注册过, 则根据手机号和密码创建新用
        except User.DoesNotExist:
            user = User.objects.create_user(username=mobile,
                                                mobile=mobile,
                                              password=password)
        # 如果手机号注册过, 则判断密码是否正确
        else:
            if not user.check_password(password):
                return http.HttpResponseBadRequest("密码不正确")

        # 4.绑定用户信息和openid
        qquser = OAuthQQUser.objects.create( user=user,
                                                            openid=openid)
        # 5.设置登陆状态
        login(request,user)

        response = redirect(reverse('contents:index'))

        response.set_cookie('username',user.username,max_age=600)
        # 6.返回首页
        return response